<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">
<script>
    (function () {
        if ('') {
            if (prompt('请输入文章密码') !== '') {
                alert('密码错误！');
                if (history.length === 1) {
                    location.replace("https://google.com"); // 这里替换成你的首页
                } else {
                    history.back();
                }
            }
        }
    })();
</script>








<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="php,">










<meta name="description" content="本文来自laravel-china 接口和抽象类的概念有点相似： 接口：一个类要实现一个接口，类中必须实现接口中定义的所有方法，接口中定义的所有方法都必须是公有。 抽象类：一个类继承抽象类，子类必须定义父类中的所有抽象方法，子类中的方法访问控制（public、protected 、private）必须和父类中一样（或者更为宽松），例如某个抽象方法被声明为受保护的，那么子类中实现的方法就应该声明为受">
<meta name="keywords" content="php">
<meta property="og:type" content="article">
<meta property="og:title" content="浅谈php设计模式">
<meta property="og:url" content="http://yoursite.com/2018/11/26/浅谈php设计模式/index.html">
<meta property="og:site_name" content="苏生不惑的博客">
<meta property="og:description" content="本文来自laravel-china 接口和抽象类的概念有点相似： 接口：一个类要实现一个接口，类中必须实现接口中定义的所有方法，接口中定义的所有方法都必须是公有。 抽象类：一个类继承抽象类，子类必须定义父类中的所有抽象方法，子类中的方法访问控制（public、protected 、private）必须和父类中一样（或者更为宽松），例如某个抽象方法被声明为受保护的，那么子类中实现的方法就应该声明为受">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2020-01-14T02:28:21.478Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="浅谈php设计模式">
<meta name="twitter:description" content="本文来自laravel-china 接口和抽象类的概念有点相似： 接口：一个类要实现一个接口，类中必须实现接口中定义的所有方法，接口中定义的所有方法都必须是公有。 抽象类：一个类继承抽象类，子类必须定义父类中的所有抽象方法，子类中的方法访问控制（public、protected 、private）必须和父类中一样（或者更为宽松），例如某个抽象方法被声明为受保护的，那么子类中实现的方法就应该声明为受">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2018/11/26/浅谈php设计模式/">



<meta name="referrer" content="never"> ​​​​


  <title>浅谈php设计模式 | 苏生不惑的博客</title>
  








</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">苏生不惑的博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2018/11/26/浅谈php设计模式/">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="苏生不惑">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="苏生不惑的博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">浅谈php设计模式</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-11-26T10:35:15+08:00">
                2018-11-26
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv"></span>次
            </span>
          

          
            <div class="post-wordcount">
              
                
                  <span class="post-meta-divider">|</span>
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  6.1k 字
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  27 分钟
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>本文来自<a href="https://laravel-china.org/articles/17805?#reply72314" target="_blank" rel="noopener">laravel-china</a></p>
<p>接口和抽象类的概念有点相似：</p>
<p>接口：一个类要实现一个接口，类中必须实现接口中定义的所有方法，接口中定义的所有方法都必须是公有。</p>
<p>抽象类：一个类继承抽象类，子类必须定义父类中的所有抽象方法，子类中的方法访问控制（public、protected 、private）必须和父类中一样（或者更为宽松），例如某个抽象方法被声明为受保护的，那么子类中实现的方法就应该声明为受保护的或者公有的，而不能定义为私有的。（私有比受保护的更高级和更严格）</p>
<p><a href="https://laravel-china.org/articles/19451" target="_blank" rel="noopener">设计模式六大原则</a></p>
<p>开放封闭原则：一个软件实体如类、模块和函数应该对扩展开放，对修改关闭。</p>
<p>里氏替换原则：所有引用基类的地方必须能透明地使用其子类的对象.</p>
<p>依赖倒置原则：高层模块不应该依赖低层模块，二者都应该依赖其抽象；抽象不应该依赖细节；细节应该依赖抽象。</p>
<p>单一职责原则：不要存在多于一个导致类变更的原因。通俗的说，即一个类只负责一项职责。</p>
<p>接口隔离原则：客户端不应该依赖它不需要的接口；一个类对另一个类的依赖应该建立在最小的接口上。</p>
<p>迪米特法则 ：一个对象应该对其他对象保持最少的了解。</p>
<h3 id="单例模式"><a href="#单例模式" class="headerlink" title="单例模式"></a>单例模式</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br></pre></td><td class="code"><pre><span class="line">&lt;?php</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 单例模式</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Singleton</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * @var self[保存实例]</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    private <span class="keyword">static</span> $instance;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * @var</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    public $mix;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * return self instance [创建一个用来实例化对象的方法]</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    public <span class="keyword">static</span> <span class="function"><span class="keyword">function</span> <span class="title">getInstace</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        var_dump(isset(self::$instance));</span><br><span class="line">        <span class="keyword">if</span> (!self::$instance <span class="keyword">instanceof</span> self) &#123;</span><br><span class="line">            self::$instance = <span class="keyword">new</span> self();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> self::$instance;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * Singleton constructor.构造函数为private，防止创建对象</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    private <span class="function"><span class="keyword">function</span> <span class="title">__construct</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        echo <span class="string">"实例初始化了"</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    private <span class="function"><span class="keyword">function</span> <span class="title">__clone</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="comment">// <span class="doctag">TODO:</span> Implement __clone() method.</span></span><br><span class="line">        trigger_error(<span class="string">'Clone is not allowed!'</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// @Test</span></span><br><span class="line">$firstSingle = Singleton::getInstace();</span><br><span class="line">$secondSingle = Singleton::getInstace();</span><br><span class="line"><span class="comment">//bool(false) 实例初始化了bool(true)</span></span><br><span class="line">$firstSingle-&gt;mix = <span class="string">'one'</span>;</span><br><span class="line"><span class="comment">//一开始mix是赋值‘one',所以打印出one</span></span><br><span class="line">print_r($firstSingle-&gt;mix);</span><br><span class="line"></span><br><span class="line"><span class="comment">//由于getInstace该方法保证了Singleton类只能有一个实例，不会再重新new，minx依然用firstSingle的，mix被改变成’two‘</span></span><br><span class="line">$secondSingle-&gt;mix = <span class="string">'two'</span>;  </span><br><span class="line">print_r($firstSingle-&gt;mix);<span class="comment">//TWO</span></span><br><span class="line">print_r($secondSingle-&gt;mix);<span class="comment">//TWO</span></span><br></pre></td></tr></table></figure>
<h3 id="简单工厂模式"><a href="#简单工厂模式" class="headerlink" title="简单工厂模式"></a>简单工厂模式</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line">&lt;?php </span><br><span class="line"><span class="comment">//简单工厂模式</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ProductA</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">  <span class="function"><span class="keyword">function</span> <span class="title">__construct</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function">  </span>&#123;</span><br><span class="line">      echo <span class="string">"I am ProductA class &lt;br&gt;"</span>;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ProductB</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">  <span class="function"><span class="keyword">function</span> <span class="title">__construct</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function">  </span>&#123;</span><br><span class="line">      echo <span class="string">"I am ProductB class &lt;br&gt;"</span>;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Factory</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">  public <span class="keyword">static</span> <span class="function"><span class="keyword">function</span> <span class="title">CreateProduct</span>(<span class="params">$name</span>)</span>&#123;</span><br><span class="line">      <span class="keyword">if</span> ($name == <span class="string">'A'</span>) &#123;</span><br><span class="line">          <span class="keyword">return</span> <span class="keyword">new</span> ProductA();</span><br><span class="line">      &#125; elseif ($name == <span class="string">'B'</span>) &#123;</span><br><span class="line">          <span class="keyword">return</span> <span class="keyword">new</span> ProductB();</span><br><span class="line">      &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line">$cat = Factory::CreateProduct(<span class="string">'A'</span>);</span><br><span class="line">$dog = Factory::CreateProduct(<span class="string">'B'</span>);</span><br></pre></td></tr></table></figure>
<h3 id="一对一抽象工厂模式"><a href="#一对一抽象工厂模式" class="headerlink" title="一对一抽象工厂模式"></a>一对一抽象工厂模式</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line">&lt;?php </span><br><span class="line">  interface Product&#123;     <span class="comment">//产品接口（核心类）</span></span><br><span class="line">      public <span class="function"><span class="keyword">function</span> <span class="title">getProduct</span>(<span class="params"></span>);</span></span><br><span class="line"><span class="function">  &#125;</span></span><br><span class="line"><span class="function">  <span class="title">class</span> <span class="title">ProductA</span> <span class="title">implements</span> <span class="title">Product</span>   //<span class="title">A</span>类产品</span></span><br><span class="line"><span class="function">  </span>&#123;</span><br><span class="line">      public <span class="function"><span class="keyword">function</span> <span class="title">getProduct</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">          echo <span class="string">"I'm ProductA &lt;br&gt;"</span>;</span><br><span class="line">      &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="class"><span class="keyword">class</span> <span class="title">ProductB</span> <span class="title">implements</span> <span class="title">Product</span>   /<span class="title">B</span>类产品</span></span><br><span class="line"><span class="class">  </span>&#123;</span><br><span class="line">      public <span class="function"><span class="keyword">function</span> <span class="title">getProduct</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">          echo <span class="string">"I'm ProductB &lt;br&gt;"</span>;</span><br><span class="line">      &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  abstract <span class="class"><span class="keyword">class</span> <span class="title">Factory</span></span>&#123;      <span class="comment">//抽象工厂类（抽象类）（核心工厂类）</span></span><br><span class="line">      abstract <span class="keyword">static</span> <span class="function"><span class="keyword">function</span> <span class="title">createProduct</span>(<span class="params"></span>);</span></span><br><span class="line"><span class="function">  &#125;</span></span><br><span class="line"><span class="function">  <span class="title">class</span> <span class="title">ProductAFactory</span> <span class="title">extends</span> <span class="title">Factory</span>   //<span class="title">A</span>工厂继承工厂类</span></span><br><span class="line"><span class="function">  </span>&#123;</span><br><span class="line">      public <span class="keyword">static</span> <span class="function"><span class="keyword">function</span> <span class="title">createProduct</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function">      </span>&#123;</span><br><span class="line">          <span class="keyword">return</span> <span class="keyword">new</span> ProductA();   <span class="comment">//A工厂创建A产品类对象</span></span><br><span class="line">      &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="class"><span class="keyword">class</span> <span class="title">ProductBFactory</span> <span class="keyword">extends</span> <span class="title">Product</span>  //<span class="title">B</span>工厂继承工厂类</span></span><br><span class="line"><span class="class">  </span>&#123;</span><br><span class="line">      public <span class="keyword">static</span> <span class="function"><span class="keyword">function</span> <span class="title">createProduct</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function">      </span>&#123;</span><br><span class="line">          <span class="keyword">return</span> <span class="keyword">new</span> ProductB();    <span class="comment">//B工厂创建B产品类对象</span></span><br><span class="line">      &#125;</span><br><span class="line">  &#125;</span><br><span class="line">    注意：声明为<span class="keyword">static</span>的静态方法不能通过<span class="keyword">new</span>实例化对象进行访问，必须使用类名::方法名() 访问</span><br><span class="line">  $ProductA = ProductAFactory::createProduct();</span><br><span class="line">  $ProductA-&gt;getProduct();</span><br><span class="line">  $ProductB = ProductBFactory::createProduct();</span><br><span class="line">  $ProductB-&gt;getProduct();</span><br></pre></td></tr></table></figure>
<h3 id="一对多抽象工厂模式"><a href="#一对多抽象工厂模式" class="headerlink" title="一对多抽象工厂模式"></a>一对多抽象工厂模式</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br></pre></td><td class="code"><pre><span class="line">&lt;?php </span><br><span class="line">interface Mouse&#123;     <span class="comment">//鼠标产品接口（核心类）</span></span><br><span class="line">      public <span class="function"><span class="keyword">function</span> <span class="title">getMouse</span>(<span class="params"></span>);  //获取鼠标</span></span><br><span class="line"><span class="function">  &#125;</span></span><br><span class="line"><span class="function"><span class="title">class</span> <span class="title">DellMouse</span> <span class="title">implements</span> <span class="title">Mouse</span>   //戴尔类产品</span></span><br><span class="line"><span class="function">  </span>&#123;</span><br><span class="line">      public <span class="function"><span class="keyword">function</span> <span class="title">getMouse</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">          echo <span class="string">"我是戴尔鼠标&lt;br&gt;"</span>;</span><br><span class="line">      &#125;</span><br><span class="line">  &#125;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">LenovoMouse</span> <span class="title">implements</span> <span class="title">Mouse</span>   //联想类产品</span></span><br><span class="line"><span class="class">  </span>&#123;</span><br><span class="line">      public <span class="function"><span class="keyword">function</span> <span class="title">getMouse</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">          echo <span class="string">"我是联想鼠标&lt;br&gt;"</span>;</span><br><span class="line">      &#125;</span><br><span class="line">  &#125;</span><br><span class="line">interface Keybo&#123;     <span class="comment">//键盘产品接口（核心类）</span></span><br><span class="line">      public <span class="function"><span class="keyword">function</span> <span class="title">getKeybo</span>(<span class="params"></span>);  //获取键盘</span></span><br><span class="line"><span class="function">  &#125;</span></span><br><span class="line"><span class="function"><span class="title">class</span> <span class="title">DellKeybo</span> <span class="title">implements</span> <span class="title">Keybo</span>   //戴尔类产品</span></span><br><span class="line"><span class="function">  </span>&#123;</span><br><span class="line">      public <span class="function"><span class="keyword">function</span> <span class="title">getKeybo</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">          echo <span class="string">"我是戴尔键盘&lt;br&gt;"</span>;</span><br><span class="line">      &#125;</span><br><span class="line">  &#125;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">LenovoKeybo</span> <span class="title">implements</span> <span class="title">Keybo</span>   //联想类产品</span></span><br><span class="line"><span class="class">  </span>&#123;</span><br><span class="line">      public <span class="function"><span class="keyword">function</span> <span class="title">getKeybo</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">          echo <span class="string">"我是联想键盘&lt;br&gt;"</span>;</span><br><span class="line">      &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">abstract <span class="class"><span class="keyword">class</span> <span class="title">Factory</span></span>&#123;      <span class="comment">//抽象工厂类（核心工厂类）</span></span><br><span class="line">      abstract <span class="keyword">static</span> <span class="function"><span class="keyword">function</span> <span class="title">createMouse</span>(<span class="params"></span>); //生产鼠标</span></span><br><span class="line"><span class="function">      <span class="title">abstract</span> <span class="title">static</span> <span class="title">function</span> <span class="title">createKeybo</span>(<span class="params"></span>);//生产键盘</span></span><br><span class="line"><span class="function">  &#125;</span></span><br><span class="line"><span class="function"><span class="title">class</span> <span class="title">DellFactory</span> <span class="title">extends</span> <span class="title">Factory</span>   //戴尔牌工厂继承工厂类</span></span><br><span class="line"><span class="function">  </span>&#123;</span><br><span class="line">      public <span class="keyword">static</span> <span class="function"><span class="keyword">function</span> <span class="title">createMouse</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function">      </span>&#123;</span><br><span class="line">          <span class="keyword">return</span> <span class="keyword">new</span> DellMouse();   <span class="comment">//工厂创建戴尔鼠标类对象</span></span><br><span class="line">      &#125;</span><br><span class="line">            public <span class="keyword">static</span> <span class="function"><span class="keyword">function</span> <span class="title">createKeybo</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function">      </span>&#123;</span><br><span class="line">          <span class="keyword">return</span> <span class="keyword">new</span> DellKeybo();   <span class="comment">//工厂创建戴尔键盘类对象</span></span><br><span class="line">      &#125;</span><br><span class="line">  &#125;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">LenovoFactory</span> <span class="keyword">extends</span> <span class="title">Factory</span>   //联想牌工厂继承工厂类</span></span><br><span class="line"><span class="class">  </span>&#123;</span><br><span class="line">      public <span class="keyword">static</span> <span class="function"><span class="keyword">function</span> <span class="title">createMouse</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function">      </span>&#123;</span><br><span class="line">          <span class="keyword">return</span> <span class="keyword">new</span> LenovoMouse();   <span class="comment">//工厂创建联想鼠标类对象</span></span><br><span class="line">      &#125;</span><br><span class="line">            public <span class="keyword">static</span> <span class="function"><span class="keyword">function</span> <span class="title">createKeybo</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function">      </span>&#123;</span><br><span class="line">          <span class="keyword">return</span> <span class="keyword">new</span> LenovoKeybo();   <span class="comment">//工厂创建联想键盘类对象</span></span><br><span class="line">      &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">//输出“我是戴尔鼠标”</span></span><br><span class="line">  $dell_mouse =DellFactory::createMouse();</span><br><span class="line">  echo  $dell_mouse-&gt;getMouse();</span><br><span class="line">  <span class="comment">//输出“我是戴尔键盘”</span></span><br><span class="line">  $dell_keybo = DellFactory::createKeybo();</span><br><span class="line">  echo $dell_keybo-&gt;getKeybo();</span><br><span class="line">  <span class="comment">//输出“我是联想鼠标”</span></span><br><span class="line">  $lenovo_mouse = LenovoFactory::createMouse();</span><br><span class="line">  echo $lenovo_mouse-&gt;getMouse();</span><br><span class="line">  <span class="comment">//输出“我是联想键盘”</span></span><br><span class="line">  $lenovo_keybo = LenovoFactory::createKeybo();</span><br><span class="line">  echo $lenovo_keybo-&gt;getKeybo();</span><br></pre></td></tr></table></figure>
<h3 id="self-static"><a href="#self-static" class="headerlink" title="self static"></a>self static</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//实例代码1</span></span><br><span class="line">&lt;?php</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">A</span></span>&#123;</span><br><span class="line">    <span class="keyword">const</span> CURRENT = <span class="string">'A'</span>;</span><br><span class="line">    <span class="keyword">const</span> A = <span class="string">'A'</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">B</span> <span class="keyword">extends</span> <span class="title">A</span></span>&#123;</span><br><span class="line">    <span class="keyword">const</span> CURRENT = <span class="string">'B'</span>;</span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">get</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        echo self::CURRENT.PHP_EOL.self::A; <span class="comment">//这儿用的self关键字</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">C</span> <span class="keyword">extends</span> <span class="title">B</span></span>&#123;</span><br><span class="line">    <span class="keyword">const</span> CURRENT = <span class="string">'C'</span>;</span><br><span class="line">&#125;</span><br><span class="line">$b = <span class="keyword">new</span> C();</span><br><span class="line">$b-&gt;get();</span><br><span class="line">$ php selfBind.php</span><br><span class="line">B</span><br><span class="line">A</span><br><span class="line"><span class="comment">//实例代码2</span></span><br><span class="line">&lt;?php</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">A</span></span>&#123;</span><br><span class="line">    <span class="keyword">const</span> CURRENT = <span class="string">'A'</span>;</span><br><span class="line">    <span class="keyword">const</span> A = <span class="string">'A'</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">B</span> <span class="keyword">extends</span> <span class="title">A</span></span>&#123;</span><br><span class="line">    <span class="keyword">const</span> CURRENT = <span class="string">'B'</span>;</span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">get</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        echo <span class="keyword">static</span>::CURRENT.PHP_EOL.static::A; <span class="comment">//这儿用的static关键字 https://www.snail-c.cn/article/2</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">C</span> <span class="keyword">extends</span> <span class="title">B</span></span>&#123;</span><br><span class="line">    <span class="keyword">const</span> CURRENT = <span class="string">'C'</span>;</span><br><span class="line">&#125;</span><br><span class="line">$b = <span class="keyword">new</span> C();</span><br><span class="line">$b-&gt;get();</span><br><span class="line">$ php selfBind.php</span><br><span class="line">C</span><br><span class="line">A</span><br></pre></td></tr></table></figure>
<h3 id="ioc"><a href="#ioc" class="headerlink" title="ioc"></a>ioc</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">IOC理论提出的观点大体是这样的：借助于“第三方”实现具有依赖关系的对象之间的解耦</span><br><span class="line">由于引进了中间位置的“第三方”，也就是IOC容器，使得A、B、C、D这<span class="number">4</span>个对象没有了耦合关系，齿轮之间的传动全部依靠“第三方”了，全部对象的控制权全部上缴给“第三方”IOC容器，所以，IOC容器成了整个系统的关键核心，它起到了一种类似“粘合剂”的作用，把系统中的所有对象粘合在一起发挥作用，如果没有这个“粘合剂”，对象与对象之间会彼此失去联系，这就是有人把IOC容器比喻成“粘合剂”的由来。</span><br><span class="line"></span><br><span class="line">软件系统在没有引入IOC容器之前，如图<span class="number">1</span>所示，对象A依赖于对象B，那么对象A在初始化或者运行到某一点的时候，自己必须主动去创建对象B或者使用已经创建的对象B。无论是创建还是使用对象B，控制权都在自己手上。</span><br><span class="line"></span><br><span class="line">软件系统在引入IOC容器之后，这种情形就完全改变了，如图<span class="number">3</span>所示，由于IOC容器的加入，对象A与对象B之间失去了直接联系，所以，当对象A运行到需要对象B的时候，IOC容器会主动创建一个对象B注入到对象A需要的地方。</span><br><span class="line"></span><br><span class="line">控制被反转之后，获得依赖对象的过程由自身管理变为了由IOC容器主动注入。于是，他给“控制反转”取了一个更合适的名字叫做“依赖注入（Dependency Injection）”。他的这个答案，实际上给出了实现IOC的方法：注入。所谓依赖注入，就是由IOC容器在运行期间，动态地将某种依赖关系注入到对象之中。</span><br><span class="line"></span><br><span class="line">所以，依赖注入(DI)和控制反转(IOC)是从不同的角度的描述的同一件事情，就是指通过引入IOC容器，利用依赖关系注入的方式，实现对象之间的解耦。</span><br><span class="line"></span><br><span class="line">https:<span class="comment">//learnku.com/articles/22769</span></span><br></pre></td></tr></table></figure>
<h3 id="多例模式"><a href="#多例模式" class="headerlink" title="多例模式"></a>多例模式</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line">abstract <span class="class"><span class="keyword">class</span> <span class="title">Multiton</span> </span>&#123; </span><br><span class="line">    private <span class="keyword">static</span> $instances = array(); </span><br><span class="line">    public <span class="keyword">static</span> <span class="function"><span class="keyword">function</span> <span class="title">getInstance</span>(<span class="params"></span>) </span>&#123; </span><br><span class="line">        $key = get_called_class() . serialize(func_get_args());</span><br><span class="line">        <span class="keyword">if</span> (!isset(self::$instances[$key])) &#123; </span><br><span class="line">            $rc = <span class="keyword">new</span> ReflectionClass(get_called_class());</span><br><span class="line">            self::$instances[$key] = $rc-&gt;newInstanceArgs(func_get_args());</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> self::$instances[$key]; </span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 该私有对象阻止实例被克隆</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    private <span class="function"><span class="keyword">function</span> <span class="title">__clone</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 该私有方法阻止实例被序列化</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    private <span class="function"><span class="keyword">function</span> <span class="title">__wakeup</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">    &#125;</span><br><span class="line">&#125; </span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Hello</span> <span class="keyword">extends</span> <span class="title">Multiton</span> </span>&#123; </span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">__construct</span>(<span class="params">$string = <span class="string">'World'</span></span>) </span>&#123; </span><br><span class="line">        echo <span class="string">"Hello $string\n"</span>; </span><br><span class="line">    &#125; </span><br><span class="line">&#125; </span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">GoodBye</span> <span class="keyword">extends</span> <span class="title">Multiton</span> </span>&#123; </span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">__construct</span>(<span class="params">$string = <span class="string">'my'</span>, $string2 = <span class="string">'darling'</span></span>) </span>&#123; </span><br><span class="line">        echo <span class="string">"Goodbye $string $string2\n"</span>; </span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">$a = Hello::getInstance(<span class="string">'World'</span>); </span><br><span class="line">$b = Hello::getInstance(<span class="string">'bob'</span>); </span><br><span class="line"><span class="comment">// $a !== $b </span></span><br><span class="line">$c = Hello::getInstance(<span class="string">'World'</span>); </span><br><span class="line"><span class="comment">// $a === $c </span></span><br><span class="line">$d = GoodBye::getInstance(); </span><br><span class="line">$e = GoodBye::getInstance();</span><br><span class="line"><span class="comment">// $d === $e </span></span><br><span class="line">$f = GoodBye::getInstance(<span class="string">'your'</span>); </span><br><span class="line"><span class="comment">// $d !== $f</span></span><br></pre></td></tr></table></figure>
<h3 id="简单工厂模式-1"><a href="#简单工厂模式-1" class="headerlink" title="简单工厂模式"></a>简单工厂模式</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br></pre></td><td class="code"><pre><span class="line">interface fruit&#123;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 生长</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">grow</span>(<span class="params"></span>);</span></span><br><span class="line"><span class="function">    /**</span></span><br><span class="line"><span class="function">     * 种植</span></span><br><span class="line"><span class="function">     */</span></span><br><span class="line"><span class="function">    <span class="title">public</span> <span class="title">function</span> <span class="title">plant</span>(<span class="params"></span>);</span></span><br><span class="line"><span class="function">    /**</span></span><br><span class="line"><span class="function">     * 收获</span></span><br><span class="line"><span class="function">     */</span></span><br><span class="line"><span class="function">    <span class="title">public</span> <span class="title">function</span> <span class="title">harvest</span>(<span class="params"></span>);</span></span><br><span class="line"><span class="function">    /**</span></span><br><span class="line"><span class="function">     * 吃</span></span><br><span class="line"><span class="function">     */</span></span><br><span class="line"><span class="function">    <span class="title">public</span> <span class="title">function</span> <span class="title">eat</span>(<span class="params"></span>);</span></span><br><span class="line"><span class="function">&#125;</span></span><br><span class="line"><span class="function"><span class="title">class</span> <span class="title">apple</span> <span class="title">implements</span> <span class="title">fruit</span></span>&#123;</span><br><span class="line">    <span class="comment">//苹果树有年龄</span></span><br><span class="line">    private $treeAge;</span><br><span class="line">    <span class="comment">//苹果有颜色</span></span><br><span class="line">    private $color;</span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">grow</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        echo <span class="string">"grape grow"</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">plant</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        echo <span class="string">"grape plant"</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">harvest</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        echo <span class="string">"grape harvest"</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">eat</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        echo <span class="string">"grape eat"</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//取苹果树的年龄</span></span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">getTreeAge</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> $<span class="keyword">this</span>-&gt;treeAge;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//设置苹果树的年龄</span></span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">setTreeAge</span>(<span class="params">$age</span>)</span>&#123;</span><br><span class="line">        $<span class="keyword">this</span>-&gt;treeAge = $age;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">grape</span> <span class="title">implements</span> <span class="title">fruit</span></span>&#123;</span><br><span class="line">    <span class="comment">//葡萄是否有籽</span></span><br><span class="line">    private $seedLess;</span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">grow</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        echo <span class="string">"apple grow"</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">plant</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        echo <span class="string">"apple plant"</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">harvest</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        echo <span class="string">"apple harvest"</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">eat</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        echo <span class="string">"apple eat"</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//有无籽取值</span></span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">getSeedLess</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> $<span class="keyword">this</span>-&gt;seedLess;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//设置有籽无籽</span></span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">setSeedLess</span>(<span class="params">$seed</span>)</span>&#123;</span><br><span class="line">        $<span class="keyword">this</span>-&gt;seedLess = $seed;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">farmer</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">    <span class="comment">//定义个静态工厂方法</span></span><br><span class="line">    public <span class="keyword">static</span> <span class="function"><span class="keyword">function</span> <span class="title">factory</span>(<span class="params">$fruitName</span>)</span>&#123;</span><br><span class="line">        <span class="keyword">switch</span> ($fruitName) &#123;</span><br><span class="line">            <span class="keyword">case</span> <span class="string">'apple'</span>:</span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">new</span> apple();</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">case</span> <span class="string">'grape'</span>:</span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">new</span> grape();</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">default</span>:</span><br><span class="line">                <span class="keyword">throw</span> <span class="keyword">new</span> badFruitException(<span class="string">"Error no the fruit"</span>, <span class="number">1</span>);</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">badFruitException</span> <span class="keyword">extends</span> <span class="title">Exception</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">    public $msg;</span><br><span class="line">    public $errType;</span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">__construct</span>(<span class="params">$msg = <span class="string">''</span> , $errType = <span class="number">1</span></span>)</span>&#123;</span><br><span class="line">        $<span class="keyword">this</span>-&gt;msg = $msg;</span><br><span class="line">        $<span class="keyword">this</span>-&gt;errType = $errType;</span><br><span class="line">    &#125;  </span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 获取水果实例化的方法</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">try</span>&#123;</span><br><span class="line">    $appleInstance = farmer::factory(<span class="string">'apple'</span>);</span><br><span class="line">    var_dump($appleInstance);</span><br><span class="line">&#125;<span class="keyword">catch</span>(badFruitException $err)&#123;</span><br><span class="line">    echo $err-&gt;msg . <span class="string">"_______"</span> . $err-&gt;errType;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="工厂模式"><a href="#工厂模式" class="headerlink" title="工厂模式"></a>工厂模式</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line">工厂模式，工厂方法或者类生成对象，而不是在代码中直接 <span class="keyword">new</span>。 \</span><br><span class="line">使用工厂模式，可以避免当改变某个类的名字或者方法之后，在调用这个类的所有的代码中都修改它的名字或者参数。</span><br><span class="line"></span><br><span class="line"> Test1.php</span><br><span class="line"> &lt;?php</span><br><span class="line"> <span class="class"><span class="keyword">class</span> <span class="title">Test1</span></span>&#123;</span><br><span class="line">      <span class="keyword">static</span> <span class="function"><span class="keyword">function</span> <span class="title">test</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">          echo __FILE__;</span><br><span class="line">      &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  Factory.php</span><br><span class="line"> &lt;?php</span><br><span class="line"> <span class="class"><span class="keyword">class</span> <span class="title">Factory</span></span>&#123;</span><br><span class="line">     <span class="comment">/*</span></span><br><span class="line"><span class="comment">      * 如果某个类在很多的文件中都new ClassName()，那么万一这个类的名字</span></span><br><span class="line"><span class="comment">      * 发生变更或者参数发生变化，如果不使用工厂模式，就需要修改每一个PHP</span></span><br><span class="line"><span class="comment">      * 代码，使用了工厂模式之后，只需要修改工厂类或者方法就可以了。</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">     <span class="keyword">static</span> <span class="function"><span class="keyword">function</span> <span class="title">createDatabase</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">         $test = <span class="keyword">new</span> Test1();</span><br><span class="line">         <span class="keyword">return</span> $test;</span><br><span class="line">     &#125;</span><br><span class="line"> &#125;</span><br><span class="line">Test.php</span><br><span class="line"> &lt;?php</span><br><span class="line"> spl_autoload_register(<span class="string">'autoload1'</span>);</span><br><span class="line"></span><br><span class="line"> $test = Factory::createDatabase();</span><br><span class="line"> $test-&gt;test();</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">autoload1</span>(<span class="params">$class</span>)</span>&#123;</span><br><span class="line">     $dir  = __DIR__;</span><br><span class="line">     $requireFile = $dir."\\".$class.".php";</span><br><span class="line">    <span class="built_in">require</span> $requireFile;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="注册模式"><a href="#注册模式" class="headerlink" title="注册模式"></a>注册模式</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">注册模式，解决全局共享和交换对象。已经创建好的对象，挂在到某个全局可以使用的数组上，在需要使用的时候，直接从该数组上获取即可。将对象注册到全局的树上。任何地方直接去访问。</span><br><span class="line"></span><br><span class="line"> &lt;?php</span><br><span class="line"></span><br><span class="line">  <span class="class"><span class="keyword">class</span> <span class="title">Register</span></span></span><br><span class="line"><span class="class">  </span>&#123;</span><br><span class="line">      protected <span class="keyword">static</span>  $objects;</span><br><span class="line">      <span class="function"><span class="keyword">function</span> <span class="title">set</span>(<span class="params">$alias,$object</span>)//将对象注册到全局的树上</span></span><br><span class="line"><span class="function">      </span>&#123;</span><br><span class="line">          self::$objects[$alias]=$object;<span class="comment">//将对象放到树上</span></span><br><span class="line">      &#125;</span><br><span class="line">     <span class="keyword">static</span> <span class="function"><span class="keyword">function</span> <span class="title">get</span>(<span class="params">$name</span>)</span>&#123;</span><br><span class="line">         <span class="keyword">return</span> self::$objects[$name];<span class="comment">//获取某个注册到树上的对象</span></span><br><span class="line">     &#125;</span><br><span class="line">     <span class="function"><span class="keyword">function</span> <span class="title">_unset</span>(<span class="params">$alias</span>)</span></span><br><span class="line"><span class="function">     </span>&#123;</span><br><span class="line">         unset(self::$objects[$alias]);<span class="comment">//移除某个注册到树上的对象。</span></span><br><span class="line">     &#125;</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>
<h3 id="适配器模式"><a href="#适配器模式" class="headerlink" title="适配器模式"></a>适配器模式</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br></pre></td><td class="code"><pre><span class="line">将各种截然不同的函数接口封装成统一的 API。 </span><br><span class="line">PHP 中的数据库操作有 MySQL,MySQLi,PDO 三种，可以用适配器模式统一成一致，使不同的数据库操作，统一成一样的 API。类似的场景还有 cache 适配器，可以将 memcache,redis,file,apc 等不同的缓存函数，统一成一致。 </span><br><span class="line">首先定义一个接口 (有几个方法，以及相应的参数)。然后，有几种不同的情况，就写几个类实现该接口。将完成相似功能的函数，统一成一致的方法。</span><br><span class="line"></span><br><span class="line">接口 IDatabase</span><br><span class="line"> &lt;?php</span><br><span class="line"> namespace IMooc;</span><br><span class="line"> interface IDatabase</span><br><span class="line"> &#123;</span><br><span class="line">     <span class="function"><span class="keyword">function</span> <span class="title">connect</span>(<span class="params">$host, $user, $passwd, $dbname</span>);</span></span><br><span class="line"><span class="function">     <span class="title">function</span> <span class="title">query</span>(<span class="params">$sql</span>);</span></span><br><span class="line"><span class="function">     <span class="title">function</span> <span class="title">close</span>(<span class="params"></span>);</span></span><br><span class="line"><span class="function"> &#125;</span></span><br><span class="line"><span class="function"><span class="title">MySQL</span></span></span><br><span class="line"><span class="function"></span></span><br><span class="line"><span class="function"> &lt;?<span class="title">php</span></span></span><br><span class="line"><span class="function">  <span class="title">namespace</span> <span class="title">IMooc</span>\<span class="title">Database</span>;</span></span><br><span class="line"><span class="function">  <span class="title">use</span> <span class="title">IMooc</span>\<span class="title">IDatabase</span>;</span></span><br><span class="line"><span class="function">  <span class="title">class</span> <span class="title">MySQL</span> <span class="title">implements</span> <span class="title">IDatabase</span></span></span><br><span class="line"><span class="function">  </span>&#123;</span><br><span class="line">      protected $conn;</span><br><span class="line">      <span class="function"><span class="keyword">function</span> <span class="title">connect</span>(<span class="params">$host, $user, $passwd, $dbname</span>)</span></span><br><span class="line"><span class="function">      </span>&#123;</span><br><span class="line">         $conn = mysql_connect($host, $user, $passwd);</span><br><span class="line">         mysql_select_db($dbname, $conn);</span><br><span class="line">         $<span class="keyword">this</span>-&gt;conn = $conn;</span><br><span class="line">     &#125;</span><br><span class="line"></span><br><span class="line">     <span class="function"><span class="keyword">function</span> <span class="title">query</span>(<span class="params">$sql</span>)</span></span><br><span class="line"><span class="function">     </span>&#123;</span><br><span class="line">         $res = mysql_query($sql, $<span class="keyword">this</span>-&gt;conn);</span><br><span class="line">         <span class="keyword">return</span> $res;</span><br><span class="line">     &#125;</span><br><span class="line"></span><br><span class="line">     <span class="function"><span class="keyword">function</span> <span class="title">close</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function">     </span>&#123;</span><br><span class="line">         mysql_close($<span class="keyword">this</span>-&gt;conn);</span><br><span class="line">     &#125;</span><br><span class="line"> &#125;</span><br><span class="line">MySQLi</span><br><span class="line"></span><br><span class="line"> &lt;?php</span><br><span class="line">  namespace IMooc\Database;</span><br><span class="line">  use IMooc\IDatabase;</span><br><span class="line">  <span class="class"><span class="keyword">class</span> <span class="title">MySQLi</span> <span class="title">implements</span> <span class="title">IDatabase</span></span></span><br><span class="line"><span class="class">  </span>&#123;</span><br><span class="line">      protected $conn;</span><br><span class="line"></span><br><span class="line">     <span class="function"><span class="keyword">function</span> <span class="title">connect</span>(<span class="params">$host, $user, $passwd, $dbname</span>)</span></span><br><span class="line"><span class="function">     </span>&#123;</span><br><span class="line">         $conn = mysqli_connect($host, $user, $passwd, $dbname);</span><br><span class="line">         $<span class="keyword">this</span>-&gt;conn = $conn;</span><br><span class="line">     &#125;</span><br><span class="line"></span><br><span class="line">     <span class="function"><span class="keyword">function</span> <span class="title">query</span>(<span class="params">$sql</span>)</span></span><br><span class="line"><span class="function">     </span>&#123;</span><br><span class="line">         <span class="keyword">return</span> mysqli_query($<span class="keyword">this</span>-&gt;conn, $sql);</span><br><span class="line">     &#125;</span><br><span class="line"></span><br><span class="line">     <span class="function"><span class="keyword">function</span> <span class="title">close</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function">     </span>&#123;</span><br><span class="line">         mysqli_close($<span class="keyword">this</span>-&gt;conn);</span><br><span class="line">     &#125;</span><br><span class="line"> &#125;</span><br><span class="line">PDO</span><br><span class="line"></span><br><span class="line"> &lt;?php</span><br><span class="line">  namespace IMooc\Database;</span><br><span class="line">  use IMooc\IDatabase;</span><br><span class="line">  <span class="class"><span class="keyword">class</span> <span class="title">PDO</span> <span class="title">implements</span> <span class="title">IDatabase</span></span></span><br><span class="line"><span class="class">  </span>&#123;</span><br><span class="line">      protected $conn;</span><br><span class="line">      <span class="function"><span class="keyword">function</span> <span class="title">connect</span>(<span class="params">$host, $user, $passwd, $dbname</span>)</span></span><br><span class="line"><span class="function">      </span>&#123;</span><br><span class="line">         $conn = <span class="keyword">new</span> \PDO(<span class="string">"mysql:host=$host;dbname=$dbname"</span>, $user, $passwd);</span><br><span class="line">         $<span class="keyword">this</span>-&gt;conn = $conn;</span><br><span class="line">     &#125;</span><br><span class="line"> <span class="function"><span class="keyword">function</span> <span class="title">query</span>(<span class="params">$sql</span>)</span></span><br><span class="line"><span class="function">     </span>&#123;</span><br><span class="line">         <span class="keyword">return</span> $<span class="keyword">this</span>-&gt;conn-&gt;query($sql);</span><br><span class="line">     &#125;</span><br><span class="line"></span><br><span class="line">     <span class="function"><span class="keyword">function</span> <span class="title">close</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function">     </span>&#123;</span><br><span class="line">         unset($<span class="keyword">this</span>-&gt;conn);</span><br><span class="line">     &#125;</span><br><span class="line"> &#125;</span><br><span class="line">通过以上案例，PHP 与 MySQL 的数据库交互有三套 API，在不同的场景下可能使用不同的 API，那么开发好的代码，换一个环境，可能就要改变它的数据库 API，那么就要改写所有的代码，使用适配器模式之后，就可以使用统一的 API 去屏蔽底层的 API 差异带来的环境改变之后需要改写代码的问题。</span><br></pre></td></tr></table></figure>
<h3 id="策略模式"><a href="#策略模式" class="headerlink" title="策略模式"></a>策略模式</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">策略模式，将一组特定的行为和算法封装成类，以适应某些特定的上下文环境。 \</span><br><span class="line">eg：假如有一个电商网站系统，针对男性女性用户要各自跳转到不同的商品类目，并且所有的广告位展示不同的广告。在传统的代码中，都是在系统中加入各种 <span class="keyword">if</span> <span class="keyword">else</span> 的判断，硬编码的方式。如果有一天增加了一种用户，就需要改写代码。使用策略模式，如果新增加一种用户类型，只需要增加一种策略就可以。其他所有的地方只需要使用不同的策略就可以。 \</span><br><span class="line">首先声明策略的接口文件，约定了策略的包含的行为。然后，定义各个具体的策略实现类。</span><br><span class="line"></span><br><span class="line"> UserStrategy.php</span><br><span class="line">  &lt;?php</span><br><span class="line">  <span class="comment">/*</span></span><br><span class="line"><span class="comment">   * 声明策略文件的接口，约定策略包含的行为。</span></span><br><span class="line"><span class="comment">   */</span></span><br><span class="line">  interface UserStrategy</span><br><span class="line">  &#123;</span><br><span class="line">      <span class="function"><span class="keyword">function</span> <span class="title">showAd</span>(<span class="params"></span>);</span></span><br><span class="line"><span class="function">      <span class="title">function</span> <span class="title">showCategory</span>(<span class="params"></span>);</span></span><br><span class="line"><span class="function"> &#125;</span></span><br><span class="line"><span class="function"> <span class="title">FemaleUser</span>.<span class="title">php</span></span></span><br><span class="line"><span class="function">  &lt;?<span class="title">php</span></span></span><br><span class="line"><span class="function">  <span class="title">require_once</span> '<span class="title">Loader</span>.<span class="title">php</span>';</span></span><br><span class="line"><span class="function">  <span class="title">class</span> <span class="title">FemaleUser</span> <span class="title">implements</span> <span class="title">UserStrategy</span></span></span><br><span class="line"><span class="function">  </span>&#123;</span><br><span class="line">      <span class="function"><span class="keyword">function</span> <span class="title">showAd</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">          echo <span class="string">"2016冬季女装"</span>;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="function"><span class="keyword">function</span> <span class="title">showCategory</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">         echo <span class="string">"女装"</span>;</span><br><span class="line">     &#125;</span><br><span class="line"> &#125;</span><br><span class="line">  MaleUser.php</span><br><span class="line">  &lt;?php</span><br><span class="line">  require_once <span class="string">'Loader.php'</span>;</span><br><span class="line">  <span class="class"><span class="keyword">class</span> <span class="title">MaleUser</span> <span class="title">implements</span> <span class="title">UserStrategy</span></span></span><br><span class="line"><span class="class">  </span>&#123;</span><br><span class="line">      <span class="function"><span class="keyword">function</span> <span class="title">showAd</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">          echo <span class="string">"IPhone6s"</span>;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="function"><span class="keyword">function</span> <span class="title">showCategory</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">         echo <span class="string">"电子产品"</span>;</span><br><span class="line">     &#125;</span><br><span class="line"> &#125;</span><br><span class="line"> Page.php<span class="comment">//执行文件</span></span><br><span class="line">  &lt;?php</span><br><span class="line">  require_once <span class="string">'Loader.php'</span>;</span><br><span class="line">  <span class="class"><span class="keyword">class</span> <span class="title">Page</span></span></span><br><span class="line"><span class="class">  </span>&#123;</span><br><span class="line">      protected $strategy;</span><br><span class="line">      <span class="function"><span class="keyword">function</span> <span class="title">index</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">          echo <span class="string">"AD"</span>;</span><br><span class="line">          $<span class="keyword">this</span>-&gt;strategy-&gt;showAd();</span><br><span class="line">         echo <span class="string">"&lt;br&gt;"</span>;</span><br><span class="line">         echo <span class="string">"Category"</span>;</span><br><span class="line">         $<span class="keyword">this</span>-&gt;strategy-&gt;showCategory();</span><br><span class="line">         echo <span class="string">"&lt;br&gt;"</span>;</span><br><span class="line">     &#125;</span><br><span class="line">     <span class="function"><span class="keyword">function</span> <span class="title">setStrategy</span>(<span class="params">UserStrategy $strategy</span>)</span>&#123;</span><br><span class="line">         $<span class="keyword">this</span>-&gt;strategy=$strategy;</span><br><span class="line">     &#125;</span><br><span class="line"> &#125;</span><br><span class="line"></span><br><span class="line"> $page = <span class="keyword">new</span> Page();</span><br><span class="line"> <span class="keyword">if</span>(isset($_GET[<span class="string">'male'</span>]))&#123;</span><br><span class="line">     $strategy = <span class="keyword">new</span> MaleUser();</span><br><span class="line"> &#125;<span class="keyword">else</span> &#123;</span><br><span class="line">     $strategy = <span class="keyword">new</span> FemaleUser();</span><br><span class="line"> &#125;</span><br><span class="line"> $page-&gt;setStrategy($strategy);</span><br><span class="line"> $page-&gt;index();</span><br></pre></td></tr></table></figure>
<h3 id="观察者模式"><a href="#观察者模式" class="headerlink" title="观察者模式"></a>观察者模式</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1</span>：观察者模式 (Observer)，当一个对象状态发生变化时，依赖它的对象全部会收到通知，并自动更新。 \</span><br><span class="line"><span class="number">2</span>：场景：一个事件发生后，要执行一连串更新操作。传统的编程方式，就是在事件的代码之后直接加入处理的逻辑。当更新的逻辑增多之后，代码会变得难以维护。这种方式是耦合的，侵入式的，增加新的逻辑需要修改事件的主体代码。 \</span><br><span class="line"><span class="number">3</span>：观察者模式实现了低耦合，非侵入式的通知与更新机制。 </span><br><span class="line"></span><br><span class="line">定义一个事件触发抽象类。</span><br><span class="line"></span><br><span class="line"> EventGenerator.php</span><br><span class="line">  &lt;?php</span><br><span class="line">  require_once <span class="string">'Loader.php'</span>;</span><br><span class="line">  abstract <span class="class"><span class="keyword">class</span> <span class="title">EventGenerator</span></span>&#123;</span><br><span class="line">      private $observers = array();</span><br><span class="line">      <span class="function"><span class="keyword">function</span> <span class="title">addObserver</span>(<span class="params">Observer $observer</span>)</span>&#123;</span><br><span class="line">          $<span class="keyword">this</span>-&gt;observers[]=$observer;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="function"><span class="keyword">function</span> <span class="title">notify</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">         foreach ($<span class="keyword">this</span>-&gt;observers <span class="keyword">as</span> $observer)&#123;</span><br><span class="line">             $observer-&gt;update();</span><br><span class="line">         &#125;</span><br><span class="line">     &#125;</span><br><span class="line"> &#125;</span><br><span class="line">定义一个观察者接口</span><br><span class="line"></span><br><span class="line">Observer.php</span><br><span class="line">&lt;?php</span><br><span class="line">require_once <span class="string">'Loader.php'</span>;</span><br><span class="line">interface Observer&#123;</span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">update</span>(<span class="params"></span>);//这里就是在事件发生后要执行的逻辑</span></span><br><span class="line"><span class="function">&#125;</span></span><br><span class="line"><span class="function"> &lt;?<span class="title">php</span></span></span><br><span class="line"><span class="function">  //一个实现了<span class="title">EventGenerator</span>抽象类的类，用于具体定义某个发生的事件</span></span><br><span class="line"><span class="function">  <span class="title">require</span> '<span class="title">Loader</span>.<span class="title">php</span>';</span></span><br><span class="line"><span class="function">  <span class="title">class</span> <span class="title">Event</span> <span class="title">extends</span> <span class="title">EventGenerator</span></span>&#123;</span><br><span class="line">      <span class="function"><span class="keyword">function</span> <span class="title">triger</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">          echo <span class="string">"Event&lt;br&gt;"</span>;</span><br><span class="line">      &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="class"><span class="keyword">class</span> <span class="title">Observer1</span> <span class="title">implements</span> <span class="title">Observer</span></span>&#123;</span><br><span class="line">     <span class="function"><span class="keyword">function</span> <span class="title">update</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">         echo <span class="string">"逻辑1&lt;br&gt;"</span>;</span><br><span class="line">     &#125;</span><br><span class="line"> &#125;</span><br><span class="line"> <span class="class"><span class="keyword">class</span> <span class="title">Observer2</span> <span class="title">implements</span> <span class="title">Observer</span></span>&#123;</span><br><span class="line">     <span class="function"><span class="keyword">function</span> <span class="title">update</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">         echo <span class="string">"逻辑2&lt;br&gt;"</span>;</span><br><span class="line">     &#125;</span><br><span class="line"> &#125;</span><br><span class="line"> $event = <span class="keyword">new</span> Event();</span><br><span class="line"> $event-&gt;addObserver(<span class="keyword">new</span> Observer1());</span><br><span class="line"> $event-&gt;addObserver(<span class="keyword">new</span> Observer2());</span><br><span class="line"> $event-&gt;triger();</span><br><span class="line"> $event-&gt;notify();</span><br><span class="line">当某个事件发生后，需要执行的逻辑增多时，可以以松耦合的方式去增删逻辑。也就是代码中的红色部分，只需要定义一个实现了观察者接口的类，实现复杂的逻辑，然后在红色的部分加上一行代码即可。这样实现了低耦合</span><br></pre></td></tr></table></figure>
<h3 id="原型模式"><a href="#原型模式" class="headerlink" title="原型模式"></a>原型模式</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br></pre></td><td class="code"><pre><span class="line">原型模式（对象克隆以避免创建对象时的消耗） \</span><br><span class="line"><span class="number">1</span>：与工厂模式类似，都是用来创建对象。 \</span><br><span class="line"><span class="number">2</span>：与工厂模式的实现不同，原型模式是先创建好一个原型对象，然后通过 clone 原型对象来创建新的对象。这样就免去了类创建时重复的初始化操作。 \</span><br><span class="line"><span class="number">3</span>：原型模式适用于大对象的创建，创建一个大对象需要很大的开销，如果每次 <span class="keyword">new</span> 就会消耗很大，原型模式仅需要内存拷贝即可。</span><br><span class="line"></span><br><span class="line">Canvas.php</span><br><span class="line">&lt;?php</span><br><span class="line">require_once <span class="string">'Loader.php'</span>;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Canvas</span></span>&#123;</span><br><span class="line">private $data;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">init</span>(<span class="params">$width = <span class="number">20</span>, $height = <span class="number">10</span></span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        $data = array();</span><br><span class="line">        <span class="keyword">for</span>($i = <span class="number">0</span>; $i &lt; $height; $i++)</span><br><span class="line">        &#123;</span><br><span class="line">            <span class="keyword">for</span>($j = <span class="number">0</span>; $j &lt; $width; $j++)</span><br><span class="line">            &#123;</span><br><span class="line">                $data[$i][$j] = <span class="string">'*'</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        $<span class="keyword">this</span>-&gt;data = $data;</span><br><span class="line">    &#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">rect</span>(<span class="params">$x1, $y1, $x2, $y2</span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        foreach($<span class="keyword">this</span>-&gt;data <span class="keyword">as</span> $k1 =&gt; $line)</span><br><span class="line">        &#123;</span><br><span class="line">            <span class="keyword">if</span> ($x1 &gt; $k1 or $x2 &lt; $k1) <span class="keyword">continue</span>;</span><br><span class="line">           foreach($line <span class="keyword">as</span> $k2 =&gt; $char)</span><br><span class="line">            &#123;</span><br><span class="line">              <span class="keyword">if</span> ($y1&gt;$k2 or $y2&lt;$k2) <span class="keyword">continue</span>;</span><br><span class="line">                $<span class="keyword">this</span>-&gt;data[$k1][$k2] = <span class="string">'#'</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">draw</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        foreach ($<span class="keyword">this</span>-&gt;data <span class="keyword">as</span> $line)&#123;</span><br><span class="line">            foreach ($line <span class="keyword">as</span> $char)&#123;</span><br><span class="line">                echo $char;</span><br><span class="line">            &#125;</span><br><span class="line">            echo <span class="string">"&lt;br&gt;;"</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"> Index.php</span><br><span class="line">  &lt;?php</span><br><span class="line">  <span class="built_in">require</span> <span class="string">'Loader.php'</span>;</span><br><span class="line">  $c = <span class="keyword">new</span> Canvas();</span><br><span class="line">  $c-&gt;init();</span><br><span class="line">  <span class="comment">// $canvas1 = new Canvas();</span></span><br><span class="line">  <span class="comment">// $canvas1-&gt;init();</span></span><br><span class="line">  $canvas1 = clone $c;<span class="comment">//通过克隆，可以省去init()方法，这个方法循环两百次</span></span><br><span class="line">  <span class="comment">//去产生一个数组。当项目中需要产生很多的这样的对象时，就会new很多的对象，那样</span></span><br><span class="line"> <span class="comment">//是非常消耗性能的。</span></span><br><span class="line"> $canvas1-&gt;rect(<span class="number">2</span>, <span class="number">2</span>, <span class="number">8</span>, <span class="number">8</span>);</span><br><span class="line"> $canvas1-&gt;draw();</span><br><span class="line"> echo <span class="string">"-----------------------------------------&lt;br&gt;"</span>;</span><br><span class="line"> <span class="comment">// $canvas2 = new Canvas();</span></span><br><span class="line"> <span class="comment">// $canvas2-&gt;init();</span></span><br><span class="line"> $canvas2 = clone $c;</span><br><span class="line"> $canvas2-&gt;rect(<span class="number">1</span>, <span class="number">4</span>, <span class="number">8</span>, <span class="number">8</span>);</span><br><span class="line"> $canvas2-&gt;draw();</span><br><span class="line"></span><br><span class="line">装饰器模式</span><br><span class="line"></span><br><span class="line"><span class="number">1</span>：装饰器模式，可以动态的添加修改类的功能 \</span><br><span class="line"><span class="number">2</span>：一个类提供了一项功能，如果要在修改并添加额外的功能，传统的编程模式，需要写一个子类继承它，并重写实现类的方法 \</span><br><span class="line"><span class="number">3</span>：使用装饰器模式，仅需要在运行时添加一个装饰器对象即可实现，可以实现最大额灵活性。</span><br><span class="line">https:<span class="comment">//learnku.com/articles/34239</span></span><br></pre></td></tr></table></figure>
<h3 id="三大经典模式"><a href="#三大经典模式" class="headerlink" title="三大经典模式"></a>三大经典模式</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Single</span> </span>&#123;</span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">index</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">''</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">$single1 = <span class="keyword">new</span> Single();</span><br><span class="line">$single2 = <span class="keyword">new</span> Single();</span><br><span class="line">var_dump($single1);</span><br><span class="line">var_dump($single2);</span><br><span class="line"><span class="keyword">if</span> ($single2 === $single1) &#123;</span><br><span class="line">    echo <span class="string">"是同一个对象"</span>;</span><br><span class="line">&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    echo <span class="string">"不是同一个对象"</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// object(Single)#1 (0) &#123;</span></span><br><span class="line"><span class="comment">// &#125;</span></span><br><span class="line"><span class="comment">// object(Single)#2 (0) &#123;</span></span><br><span class="line"><span class="comment">// &#125;</span></span><br><span class="line"><span class="comment">// 不是同一个对象</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Single2</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 1.声明一个静态属性，用户保存类的实例</span></span><br><span class="line">    public <span class="keyword">static</span> $instance;</span><br><span class="line">    <span class="comment">//3. 将构函数私有化，避免外部new(每new一次，就不是同一个实例)</span></span><br><span class="line">    private <span class="function"><span class="keyword">function</span> <span class="title">__construct</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 2.声明一个静态的公共方法，用户外部调用本类的实例</span></span><br><span class="line">    public <span class="keyword">static</span> <span class="function"><span class="keyword">function</span> <span class="title">getInstance</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (!(self::$instance <span class="keyword">instanceof</span> self)) &#123;</span><br><span class="line">            self::$instance = <span class="keyword">new</span> self;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> self::$instance;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//3. 克隆函数私有化，避免外部clone(每clone一次，就不是同一个实例)</span></span><br><span class="line">    private <span class="function"><span class="keyword">function</span> <span class="title">__clone</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">$singleDemo1 = Single2::getInstance();</span><br><span class="line">$singleDemo2 = Single2::getInstance();</span><br><span class="line">var_dump($singleDemo1-&gt;getInstance());</span><br><span class="line">var_dump($singleDemo2-&gt;getInstance());</span><br><span class="line"><span class="keyword">if</span> ($singleDemo1 === $singleDemo2) &#123;</span><br><span class="line">    echo <span class="string">"是同一个对象"</span>;</span><br><span class="line">&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    echo <span class="string">"不是同一个对象"</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// object(Single2)#3 (0) &#123;</span></span><br><span class="line"><span class="comment">// &#125;</span></span><br><span class="line"><span class="comment">// object(Single2)#3 (0) &#123;</span></span><br><span class="line"><span class="comment">// &#125;</span></span><br><span class="line"><span class="comment">// 是同一个对象</span></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 工厂模式</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Factory</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">    public <span class="keyword">static</span> <span class="function"><span class="keyword">function</span> <span class="title">createObj</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> Single::getInstance(<span class="string">'个人技术'</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment"> * 注册模式</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment"> * 含义:就是将对象放在一个对象池中，使用的时候直接去对象池查找.</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment"> * 需要如下几个操作:</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment"> * 1.注册</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment"> * 2.存放对象池</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment"> * 3.获取</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment"> * 4.销毁</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line">Class Register</span><br><span class="line">&#123;</span><br><span class="line">    <span class="comment">// 用一个数组来当做对象池，键当做对象别名，值存储具体对象</span></span><br><span class="line">    public <span class="keyword">static</span> $objTree = [];</span><br><span class="line">    <span class="comment">// 将对象放在对象池</span></span><br><span class="line">    public <span class="keyword">static</span> <span class="function"><span class="keyword">function</span> <span class="title">set</span>(<span class="params">$key, $val</span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> self::$objTree[$key] = $val;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 通过对象别名在对象池中获取到对象别名</span></span><br><span class="line">    public <span class="keyword">static</span> <span class="function"><span class="keyword">function</span> <span class="title">get</span>(<span class="params">$key</span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> self::$objTree[$key];</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 通过对象别名将对象从对象池中注销</span></span><br><span class="line">    public <span class="keyword">static</span> <span class="function"><span class="keyword">function</span> <span class="title">_unset</span>(<span class="params">$key</span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        unset(self::$objTree[$key]);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">Register::set(<span class="string">'single'</span>, <span class="attr">Factory</span>::createObj());</span><br><span class="line">$single = Register::get(<span class="string">'single'</span>);</span><br><span class="line">print_r($single);</span><br><span class="line">echo $single::$attribute;</span><br><span class="line">https:<span class="comment">//learnku.com/articles/36134</span></span><br></pre></td></tr></table></figure>
<h3 id="接口隔离"><a href="#接口隔离" class="headerlink" title="接口隔离"></a>接口隔离</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br></pre></td><td class="code"><pre><span class="line">客户端不应当被迫实现它不需要用到的接口</span><br><span class="line">工作接口</span><br><span class="line"></span><br><span class="line">interface WorkableInterface</span><br><span class="line">&#123;</span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">work</span>(<span class="params"></span>);</span></span><br><span class="line"><span class="function">&#125;</span></span><br><span class="line"><span class="function">睡觉接口</span></span><br><span class="line"><span class="function"></span></span><br><span class="line"><span class="function"><span class="title">interface</span> <span class="title">SleepableInterface</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">sleep</span>(<span class="params"></span>);</span></span><br><span class="line"><span class="function">&#125;</span></span><br><span class="line"><span class="function">工人和机器根据自身情况去实现这些接口</span></span><br><span class="line"><span class="function"></span></span><br><span class="line"><span class="function"><span class="title">class</span> <span class="title">HumanWorker</span> <span class="title">implements</span> <span class="title">WorkableInterface</span>, <span class="title">SleepableInterface</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">work</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">'human working.'</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">sleep</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">'human sleeping'</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">AndroidWorker</span> <span class="title">implements</span> <span class="title">WorkableInterface</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">work</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">'android working.'</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">beManaged</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        $<span class="keyword">this</span>-&gt;work();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">机长</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Captain</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">manage</span>(<span class="params">$worker</span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">if</span>($worker <span class="keyword">instanceof</span> WorkableInterface)&#123;</span><br><span class="line">            $worker-&gt;work();</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span>($worker <span class="keyword">instanceof</span> SleepableInterface)&#123;</span><br><span class="line">            $worker-&gt;sleep();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">https:<span class="comment">//learnku.com/articles/39202</span></span><br></pre></td></tr></table></figure>
<h3 id="开放封闭"><a href="#开放封闭" class="headerlink" title="开放封闭"></a>开放封闭</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br></pre></td><td class="code"><pre><span class="line">对扩展开放，是指代码应当很容易添加新功能。</span><br><span class="line">对修改封闭，是指我们在添加新功能的时候尽量不会涉及到原有代码的改动。</span><br><span class="line">interface Shape &#123;</span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">area</span>(<span class="params"></span>);</span></span><br><span class="line"><span class="function">&#125;</span></span><br><span class="line"><span class="function"><span class="title">class</span> <span class="title">Square</span> <span class="title">implements</span> <span class="title">Shape</span> </span>&#123;</span><br><span class="line">    public $width;</span><br><span class="line"></span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">__construct</span>(<span class="params">$width</span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        $<span class="keyword">this</span>-&gt;width = $width;</span><br><span class="line">    &#125;</span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">area</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> $<span class="keyword">this</span>-&gt;width * $<span class="keyword">this</span>-&gt;width;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Circle</span> <span class="title">implements</span> <span class="title">Square</span> </span>&#123;</span><br><span class="line">    public $radios;</span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">__construct</span>(<span class="params">$radios</span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        $<span class="keyword">this</span>-&gt;radios = $radios;</span><br><span class="line">    &#125;</span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">area</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> $<span class="keyword">this</span>-&gt;radios * $<span class="keyword">this</span>-&gt;radios * pi();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">AreaCalculator 不再依赖于具体的行为，不需要去考虑不同形状的面积如何计算，只只需依赖于抽象的接口</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">AreaCalculator</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">calculate</span>(<span class="params">$shapes</span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        foreach($shapes <span class="keyword">as</span> $shape)</span><br><span class="line">        &#123;</span><br><span class="line">            $area[] = $shape-&gt;area();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> array_sum($area);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">将变化的「支付方式」抽象出来，隐藏于接口背后</span><br><span class="line"></span><br><span class="line">interface PaymentMethodInterface</span><br><span class="line">&#123;</span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">acceptPayment</span>(<span class="params">$receipt</span>);</span></span><br><span class="line"><span class="function">&#125;</span></span><br><span class="line"><span class="function">不同的支付方式去实现该接口，例如现金支付</span></span><br><span class="line"><span class="function"></span></span><br><span class="line"><span class="function"><span class="title">class</span> <span class="title">CashPaymentMethod</span> <span class="title">implements</span> <span class="title">PaymentMethodInterface</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">acceptPayment</span>(<span class="params">$receipt</span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="comment">// 接受现金支付</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">结账类不需要依赖具体的支付方式，只需要依赖抽象的支付接口即可</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Checkout</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">begin</span>(<span class="params">Receipt $receipt, PaymentMethodInterface $paymentMethod</span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        $paymentMethod-&gt;acceptPayment($receipt);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">https:<span class="comment">//learnku.com/articles/39065</span></span><br></pre></td></tr></table></figure>
<h3 id="组合模式"><a href="#组合模式" class="headerlink" title="组合模式"></a>组合模式</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Class CentralSystem  中央官制抽象类，其子类必须实现抽象方法</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line">abstract  <span class="class"><span class="keyword">class</span> <span class="title">CentralSystem</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">    <span class="comment">// 当前类名字</span></span><br><span class="line">    protected $name;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 构造函数，初始化$name</span></span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">__construct</span>(<span class="params">$name</span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        $<span class="keyword">this</span>-&gt;name = $name;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 获得类名字</span></span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">getName</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> $<span class="keyword">this</span>-&gt;name;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 添加子节点</span></span><br><span class="line">    abstract public <span class="function"><span class="keyword">function</span> <span class="title">add</span>(<span class="params">CentralSystem $centralSystem</span>);</span></span><br><span class="line"><span class="function"></span></span><br><span class="line"><span class="function">    // 移除子节点</span></span><br><span class="line"><span class="function">    <span class="title">abstract</span> <span class="title">public</span> <span class="title">function</span> <span class="title">remove</span>(<span class="params">CentralSystem $centralSystem</span>);</span></span><br><span class="line"><span class="function"></span></span><br><span class="line"><span class="function">    // 循环当前节点的子节点</span></span><br><span class="line"><span class="function">    <span class="title">abstract</span> <span class="title">public</span> <span class="title">function</span> <span class="title">show</span>(<span class="params">$deep</span>);</span></span><br><span class="line"><span class="function">&#125;</span></span><br><span class="line"><span class="function">/**</span></span><br><span class="line"><span class="function"> * <span class="title">Class</span> <span class="title">Emperor</span> 皇帝类，相当于树的根节点<span class="title">root</span></span></span><br><span class="line"><span class="function"> */</span></span><br><span class="line"><span class="function"><span class="title">class</span> <span class="title">Emperor</span> <span class="title">extends</span> <span class="title">CentralSystem</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="comment">// 存放其子节点</span></span><br><span class="line">    protected $office = [];</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * @param CentralSystem $centralSystem  添加子节点，将子节点放在数组</span></span><br><span class="line"><span class="comment">     * @throws Exception</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">add</span>(<span class="params">CentralSystem $centralSystem</span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="comment">// 获取新节点的名字</span></span><br><span class="line">        $office_name = $centralSystem-&gt;getName();</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (in_array($office_name, $<span class="keyword">this</span>-&gt;office)) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> Exception($office_name . <span class="string">'节点已经存在'</span>);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            $<span class="keyword">this</span>-&gt;office[$office_name] = $centralSystem;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * @param CentralSystem $centralSystem 移除子节点，将子节点从数组中移除</span></span><br><span class="line"><span class="comment">     * @throws Exception</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">remove</span>(<span class="params">CentralSystem $centralSystem</span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="comment">// 获取新节点的名字</span></span><br><span class="line">        $office_name = $centralSystem-&gt;getName();</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (in_array($office_name, $<span class="keyword">this</span>-&gt;office)) &#123;</span><br><span class="line">            unset($<span class="keyword">this</span>-&gt;office[$office_name]);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> Exception($office_name . <span class="string">'节点不存在'</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * @param int $deep 重复字符'-'的次数</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">show</span>(<span class="params">$deep = <span class="number">0</span></span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        echo str_repeat(<span class="string">'-'</span>, $deep) . $<span class="keyword">this</span>-&gt;name;</span><br><span class="line">        echo <span class="string">"&lt;/br&gt;"</span>;</span><br><span class="line">        <span class="comment">// 循环子节点的 节点数组$office</span></span><br><span class="line">        foreach ($<span class="keyword">this</span>-&gt;office <span class="keyword">as</span> $item) &#123;</span><br><span class="line">            $item-&gt;show($deep + <span class="number">4</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Class CompositeTest  组合模式测试----唐朝三省六部制</span></span><br><span class="line"><span class="comment"> * 结果：</span></span><br><span class="line"><span class="comment"> * 唐太宗</span></span><br><span class="line"><span class="comment"> * ----门下省</span></span><br><span class="line"><span class="comment"> * ----中书省</span></span><br><span class="line"><span class="comment"> * ----尚书省</span></span><br><span class="line"><span class="comment"> * --------吏部</span></span><br><span class="line"><span class="comment"> * --------户部</span></span><br><span class="line"><span class="comment"> * --------礼部</span></span><br><span class="line"><span class="comment"> * --------兵部</span></span><br><span class="line"><span class="comment"> * --------刑部</span></span><br><span class="line"><span class="comment"> * --------工部</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">CompositeTest</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">test</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="comment">// 唐太宗相当于根节点root</span></span><br><span class="line">        $emperor = <span class="keyword">new</span> Emperor(<span class="string">'唐太宗'</span>);</span><br><span class="line">        <span class="comment">// 唐太宗下的三个子节点：门下省、尚书省、中书省</span></span><br><span class="line">        $emperor-&gt;add(<span class="keyword">new</span> Province(<span class="string">'门下省'</span>));</span><br><span class="line">        $emperor-&gt;add(<span class="keyword">new</span> Province(<span class="string">'中书省'</span>));</span><br><span class="line">        $shangshu = <span class="keyword">new</span> Province(<span class="string">'尚书省'</span>);     <span class="comment">// 这里单独赋值是因为“尚书省”要另外添加子节点</span></span><br><span class="line">        $emperor-&gt;add($shangshu);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 尚书省添加六部</span></span><br><span class="line">        $shangshu-&gt;add(<span class="keyword">new</span> Ministries(<span class="string">'吏部'</span>));</span><br><span class="line">        $shangshu-&gt;add(<span class="keyword">new</span> Ministries(<span class="string">'户部'</span>));</span><br><span class="line">        $shangshu-&gt;add(<span class="keyword">new</span> Ministries(<span class="string">'礼部'</span>));</span><br><span class="line">        $shangshu-&gt;add(<span class="keyword">new</span> Ministries(<span class="string">'兵部'</span>));</span><br><span class="line">        $shangshu-&gt;add(<span class="keyword">new</span> Ministries(<span class="string">'刑部'</span>));</span><br><span class="line">        $shangshu-&gt;add(<span class="keyword">new</span> Ministries(<span class="string">'工部'</span>));</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 循环唐太宗的子节点数组，其子节点又有自己的子节点。</span></span><br><span class="line">        $emperor-&gt;show();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">https:<span class="comment">//learnku.com/articles/39635</span></span><br></pre></td></tr></table></figure>
<p><a href="https://learnku.com/articles/33463" target="_blank" rel="noopener">大话 PHP 设计模式</a></p>
<p><a href="https://github.com/guijianshi/DesignPattern" target="_blank" rel="noopener">php设计模式</a></p>
<p><a href="https://learnku.com/articles/24372" target="_blank" rel="noopener">设计模式之三种工厂模式</a></p>
<p><a href="https://laravel-china.org/articles/21370" target="_blank" rel="noopener">通俗易懂的设计模式</a></p>
<p> <a href="https://segmentfault.com/a/1190000014430417#articleHeader27" target="_blank" rel="noopener"> PHP面向对象编程：面向对象概念、基本实践、高级实战、PHP面向对象特殊实践</a></p>
<p><a href="https://laravel-china.org/docs/php-design-patterns/2018" target="_blank" rel="noopener">PHP 设计模式全集 2018</a></p>
<p><a href="https://www.awaimai.com/patterns/basic" target="_blank" rel="noopener">PHP 设计模式基础</a></p>
<p><a href="https://segmentfault.com/a/1190000004067581" target="_blank" rel="noopener">PHP经验总结 - 聊聊面向对象</a></p>
<p><a href="https://learnku.com/articles/12555/laravel-source-code-reading-guide-reflection-and-dependency-injection-for-class-php" target="_blank" rel="noopener">Laravel 源码阅读指南 – PHP 类的反射和依赖注入</a></p>
<p><a href="https://learnku.com/articles/24982#topnav" target="_blank" rel="noopener">设计模式超级简单的解释</a></p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/php/" rel="tag"># php</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/11/23/基本数据结构算法/" rel="next" title="基本数据结构算法">
                <i class="fa fa-chevron-left"></i> 基本数据结构算法
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/11/28/多版本php/" rel="prev" title="多版本php">
                多版本php <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
          <div class="comments" id="comments">
             <div id="gitment-container"></div>
         </div>
  




        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">苏生不惑</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">382</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">37</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/sushengbuhuo" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mysusheng@gmail.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://plus.google.com/mysusheng" target="_blank" title="Google">
                      
                        <i class="fa fa-fw fa-google"></i>Google</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-block">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                Links
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="http://v2ex.com/" title="v2ex" target="_blank">v2ex</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.fanhaobai.com/" title="fanhaobai" target="_blank">fanhaobai</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://yuanxuxu.com/archives/" title="yuanxuxu" target="_blank">yuanxuxu</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.snail-c.cn/article" title="snail-c" target="_blank">snail-c</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://showcj.com/archives" title="showcj" target="_blank">showcj</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://vultr.aicnm.com/%E6%9C%80%E6%96%B0Vultr%E6%B3%A8%E5%86%8C%E5%8F%8AVPS%E8%B4%AD%E4%B9%B0%E5%9B%BE%E6%96%87%E6%95%99%E7%A8%8B/" title="vultr" target="_blank">vultr</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.lucissfer.com/" title="lucissfer" target="_blank">lucissfer</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://blog.csdn.net/fdipzone/article/details/79352685" title="傲雪星枫" target="_blank">傲雪星枫</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.yoby123.cn/index.php/category/default/" title="小白的分享" target="_blank">小白的分享</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.cnblogs.com/52fhy/p/5819995.html" title="PHP攻城狮" target="_blank">PHP攻城狮</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://blog.jiaojie.site/" title="php" target="_blank">php</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://sphard.com/archives/" title="sphard" target="_blank">sphard</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://yuanxuxu.com/archives/" title="LNMP技术栈笔记" target="_blank">LNMP技术栈笔记</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.coding10.com/" title="学习 Laravel" target="_blank">学习 Laravel</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://shuwoom.com/?page_id=929" title="区块链学习指南" target="_blank">区块链学习指南</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://greenlightt.github.io/archives/" title="greenlightt" target="_blank">greenlightt</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.0php.net/archives/" title="0php" target="_blank">0php</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.fordba.com/category/mysql" title="mysql" target="_blank">mysql</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.itcodemonkey.com/" title="程序员" target="_blank">程序员</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.yanshuo.me/r/v2ex" title="言说" target="_blank">言说</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.timiguo.com/archive.html" title="提米果的博客" target="_blank">提米果的博客</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://phpartisan.cn/news/112.html" title="phpartisan" target="_blank">phpartisan</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.cnblogs.com/52fhy/" title="飞鸿影" target="_blank">飞鸿影</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.54php.cn/" title="54php" target="_blank">54php</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.lazyman.vip/" title="营销" target="_blank">营销</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.njphper.com/archives/" title="做人呢最重要的就是开心" target="_blank">做人呢最重要的就是开心</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.h57.pw/" title="php 初心者" target="_blank">php 初心者</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#单例模式"><span class="nav-number">1.</span> <span class="nav-text">单例模式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#简单工厂模式"><span class="nav-number">2.</span> <span class="nav-text">简单工厂模式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#一对一抽象工厂模式"><span class="nav-number">3.</span> <span class="nav-text">一对一抽象工厂模式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#一对多抽象工厂模式"><span class="nav-number">4.</span> <span class="nav-text">一对多抽象工厂模式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#self-static"><span class="nav-number">5.</span> <span class="nav-text">self static</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#ioc"><span class="nav-number">6.</span> <span class="nav-text">ioc</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#多例模式"><span class="nav-number">7.</span> <span class="nav-text">多例模式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#简单工厂模式-1"><span class="nav-number">8.</span> <span class="nav-text">简单工厂模式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#工厂模式"><span class="nav-number">9.</span> <span class="nav-text">工厂模式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#注册模式"><span class="nav-number">10.</span> <span class="nav-text">注册模式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#适配器模式"><span class="nav-number">11.</span> <span class="nav-text">适配器模式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#策略模式"><span class="nav-number">12.</span> <span class="nav-text">策略模式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#观察者模式"><span class="nav-number">13.</span> <span class="nav-text">观察者模式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#原型模式"><span class="nav-number">14.</span> <span class="nav-text">原型模式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#三大经典模式"><span class="nav-number">15.</span> <span class="nav-text">三大经典模式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#接口隔离"><span class="nav-number">16.</span> <span class="nav-text">接口隔离</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#开放封闭"><span class="nav-number">17.</span> <span class="nav-text">开放封闭</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#组合模式"><span class="nav-number">18.</span> <span class="nav-text">组合模式</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

<div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">苏生不惑</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>



<div>
<span id="showDays"></span>

</div>

<span id="busuanzi_container_site_pv">
   总访问量:<span id="busuanzi_value_site_pv"></span>次
</span>



  <span class="post-meta-divider">|</span>



<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count">博客全站共773.8k字</span>
</div>
<script>
var birthDay = new Date("11/20/2018");
var now = new Date();
var duration = now.getTime() - birthDay.getTime();
var total= Math.floor(duration / (1000 * 60 * 60 * 24));
document.getElementById("showDays").innerHTML = "本站已运行 "+total+" 天";
</script>

        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人次
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  











<script type="text/javascript">
    (function() {
        // 匿名函数，防止污染全局变量
        var utterances = document.createElement('script');
        utterances.type = 'text/javascript';
        utterances.async = true;
        utterances.setAttribute('issue-term','0')
        utterances.setAttribute('theme','')
        utterances.setAttribute('repo','sushengbuhuo/laravel_ioc_demo')
        utterances.crossorigin = 'anonymous';
        utterances.src = 'https://utteranc.es/client.js';
        // content 是要插入评论的地方
        document.getElementById('gitment-container').appendChild(utterances);
    })();
</script>


  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

  
<script>
  ((window.gitter = {}).chat = {}).options = {
    //room替换成自己的聊天室名称即可，room的名称规则是：username/roomname
    room: 'sushengbuhuo-chat/mychat'
  };
</script>
<script src="https://sidecar.gitter.im/dist/sidecar.v1.js" async defer></script>

</body>
</html>
